package com.zxw.auth.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zxw.common.api.ApiResult;
import com.zxw.common.entity.user.UserVO;
import com.zxw.common.enums.ResultCode;
import com.zxw.common.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Slf4j
@Configuration
public class SuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        log.info("登陆成功：{}", JSON.toJSONString(ApiResult.success(ResultCode.SUCCESS, authentication)));

        Object principal = authentication.getPrincipal();
        Map<String, Object> jsonMap = JSONUtil.parseJSONstr2Map(JSON.toJSONString(principal));
        Object jsonUser = jsonMap.get("userVO");
        UserVO userVO = JSON.parseObject(JSON.toJSONString(jsonUser), UserVO.class);

        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        PrintWriter printWriter = response.getWriter();
        printWriter.append(new ObjectMapper().writeValueAsString(ApiResult.success(ResultCode.LOGIN_SUCCESS,userVO)));
    }
}
